import { validate, validateOldPwd } from "@/service/api/user";
import { validateRole } from "@/service/api/role";
import { validateDept } from "@/service/api/dept";
import eventBus from "./event-bus";
import { strIsAllNumber, isMoney, isTwoPlaces } from "./string";
import { REGEXP_PHONENUM, REGEXP_EMAIL, PASSWORD } from "./regexp";
import { toArray } from "./transform";

//为保证在修改用户操作时不会回复重复信息，因为当没有userId为查询条件时，
//数据库本来就存在相同的数据，不想修改username或personNumber数据时就会回复重复的信息
let empId = null;
let roleId = null;
let deptId = null;
let parentLevel = null;
let postIdsLength = 0;
let password1 = null;

eventBus.on('updateEmpId', (id) => {
    empId = id;
})

eventBus.on('updateRoleId', (id) => {
    roleId = id;
})

eventBus.on('updateDeptId', ({ id, pL }) => {
    deptId = id;
    parentLevel = pL
})

eventBus.on('updatePostIds', (length) => {
    postIdsLength = length;
})

eventBus.on('updatePassword1', (pwd) => {
    password1 = pwd;
})

/**
 * 验证用户名是否重复
 */
export const validateUsername = async (rule, value, callback) => {
    if (value) {
        const searchForm = { username: value, id: userId };
        const data = await validate(searchForm);
        if (data.code === 100) return callback(new Error(`${data.message}，请重新填写`))
    }
};

/**
 * 验证部门名称是否重复
 */
export const validateDeptName = async (rule, value, callback) => {
    if (value) {
        const searchForm = { deptName: value, id: deptId, parentLevel: parentLevel }
        const data = await validateDept(searchForm);
        if (data.code === 100) return callback(new Error(`${data.message}，请重新填写`))
    }
};

/**
 * 验证角色名称是否重复
 */
export const validateRoleName = async (rule, value, callback) => {
    if (value) {
        const searchForm = { roleName: value, id: roleId };
        const data = await validateRole(searchForm);
        if (data.code === 100) return callback(new Error(`${data.message}，请重新填写`))
    }
};

/**
 * 验证旧密码是否正确
 */
export const validateOpwd = async (rule, value, callback) => {
    if (value) {
        const data = await validateOldPwd(value);
        if (data.code === 100) return callback(new Error(`${data.message}，请重新填写`))
    }
};

/**
 * 验证两次密码是否一样
 */
export const validatePwd2 = async (rule, value, callback) => {
    if (value !== password1) return callback(new Error('两次密码填写不一致，请重新填写'))
    if (!PASSWORD.test(value)) return callback(new Error('密码长度不少于6位，且必须包含数字，大小写字母，特殊字符'))
};

/**
 * 验证工号是否重复
 */
export const validateNum = async (rule, value, callback) => {
    // if (!strIsAllNumber(value)) {
    //     callback(new Error('工号只能为数字，请重新填写'))
    // }
    if (value) {
        const searchForm = { num: value, id: empId };
        const data = await validate(searchForm);
        if (data.code === 100) return callback(new Error(`${data.message}，请重新填写`))
    }
};

/**
 * 验证比例是否重复
 */
export const validatePercents = async (rule, value, callback) => {
    const percents = toArray(value);
    if (percents.length !== postIdsLength) return callback(new Error('比例个数与岗位个数不一致，请重新填写'));
    const total = percents.reduce((accumulator, currentValue) => {
        return accumulator + currentValue;
    }, 0)
    if (total !== 100) return callback(new Error('比例总和不为100，请重新填写'));
};

/**
 * 验证是否全为数字
 */
export const validateNumber = async (rule, value, callback) => {
    if (!strIsAllNumber(value)) {
        return callback(new Error('只能为数字，请重新填写'))
    }
};

/**
 * 验证金额格式是否正确
 */
export const validateMoney = async (rule, value, callback) => {

    if (!isMoney(value)) return callback(new Error('格式错误，请重新填写'));

    if (!isTwoPlaces(value)) return callback(new Error('默认保留小数点后两位，请重新填写'));
};

/**
 * 验证分数格式是否正确
 */
export const validateScore = async (rule, value, callback) => {
    if (!isMoney(value)) return callback(new Error('格式错误，请重新填写'));

    if (!isTwoPlaces(value)) return callback(new Error('默认保留小数点后两位，请重新填写'));

    let score = toArray(value);
    if (score[0] > 100) return callback(new Error('分数不能超过100，请重新填写'));
};

/** 创建自定义错误信息的必填表单规则 */
export const createRequiredFormRule = (message = '不能为空', trigger = 'blur') => ({
    required: true, message, trigger
});

export const rules = {
    username: [
        createRequiredFormRule('用户名不能为空'),
        { validator: validateUsername, trigger: 'blur' }
    ],
    name: [createRequiredFormRule('姓名不能为空')],
    num: [
        createRequiredFormRule('工号不能为空'),
        { validator: validateNum, trigger: 'blur' }
    ],
    phoneNum1: [
        createRequiredFormRule('联系电话1不能为空'),
        { pattern: REGEXP_PHONENUM, message: '手机号格式错误', trigger: 'blur' }
    ],
    phoneNum2: [
        { pattern: REGEXP_PHONENUM, message: '手机号格式错误', trigger: 'blur' }
    ],
    roleId: [createRequiredFormRule('权限不能为空')],
    superDept: [createRequiredFormRule('上级部门不能为空')],
    deptName: [
        createRequiredFormRule('部门名称不能为空'),
        { validator: validateDeptName, trigger: 'blur' }
    ],
    roleName: [
        createRequiredFormRule('职务名称不能为空'),
        { validator: validateRoleName, trigger: 'blur' }
    ],
    deptId: [createRequiredFormRule('部门不能为空')],
    regionId: [createRequiredFormRule('地区不能为空')],
    postId: [createRequiredFormRule('岗位不能为空')],
    percents: [
        createRequiredFormRule('比例不能为空'),
        { validator: validatePercents, trigger: 'blur' }
    ],
    grade: [createRequiredFormRule('级别不能为空')],
    idNum: [createRequiredFormRule('身份证号不能为空')],
    birthday: [createRequiredFormRule('出生日期不能为空')],
    email: [
        createRequiredFormRule('邮箱地址不能为空'),
        { pattern: REGEXP_EMAIL, message: '邮箱格式错误', trigger: 'blur' }
    ],
    oldPassword: [
        createRequiredFormRule('旧密码不能为空'),
        { validator: validateOpwd, trigger: 'blur' }
    ],
    password1: [
        createRequiredFormRule('新密码不能为空'),
        { pattern: PASSWORD, message: '密码长度不少于6位，且必须包含数字，大小写字母，特殊字符', trigger: 'blur' }
    ],
    password2: [
        createRequiredFormRule('再次输入密码不能为空'),
        { validator: validatePwd2, trigger: 'blur' }
    ]
}

export default rules